<template>
  <div class="add-product-dialog">

    <el-dialog
        v-model="dialogVisible"
        :before-close="handleClose"
        :title="title"
        width="850px"
    >

      <el-form
          ref="ruleForm"
          :inline="true"
          :model="formData"
          :rules="rules"
          class="demo-ruleForm"
          label-width="130px"
      >
        <el-row>

          <el-col :span="12">
            <el-form-item
                label="产品名称"
                prop="productPopularName"
            >
              <product-popover
                  :disabled="!dialogVisible"
                  :searchs="formData.productPopularName"
                  @confirm="productConfirm"
              >
                <el-input
                    v-model="formData.productPopularName"
                    clearable
                    placeholder="请输入产品名称"
                    @clear="productClear"
                />
              </product-popover>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="批准文号">

              <el-input
                  v-model="formData.approvalNumber"
                  disabled=""
                  placeholder="批准文号"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="包装规格">
              <el-input
                  v-model="formData.packSpecs"
                  disabled=""
                  placeholder="包装规格"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item
                label="可营销终端"
                prop="terminalType"
            >
              <el-select
                  v-model="formData.terminalType"
                  placeholder="请选择营销终端"
              >
                <el-option
                    v-for="item in appOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item
                :label="type == 'agent'?'代理属性':'兼职属性'"
                prop="agentAttribute"
            >
              <el-select
                  v-model="formData.agentAttribute"
                  :placeholder="type == 'agent'?'请选择代理属性':'请选择兼职属性'"
                  @change="attributeChange"
              >
                <template v-if="type == 'agent'">
                  <el-option
                      v-for="item in attributeOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                  />
                </template>
                <template v-else>
                  <el-option
                      v-for="item in personOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                  />
                </template>

              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item
                label="代理地区"
                prop="areas"
            >
              <el-cascader
                  ref="cascader"
                  v-model="formData.areas"
                  :options="citys"
                  :popper-append-to-body="false"
                  :props="props1"
                  clearable
                  collapse-tags
                  placeholder="请选择地区"
                  @change="areaChange"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item
                label="交易价"
                prop="tradePrice"
            >

              <price-input
                  v-model:data="formData.tradePrice"
                  :unit-str="formData.sellUnit ? '元/' + getLabel('sell_unit',formData.sellUnit) : ''"
                  is-unit
                  placeholder="请输入交易价"
              />
              <!--                            <div class="special-input">-->

              <!--                                <price-input v-model:data="formData.tradePrice" placeholder="请输入交易价" is-unit :unitStr="formData.sellUnit ? '元/' + formData.sellUnit : ''"></price-input>-->

              <!--&lt;!&ndash;                                <a style="color: dodgerblue">查看产品价格</a>&ndash;&gt;-->

              <!--                            </div>-->

            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item
                :label="type == 'agent'?'代理期限至':'兼职期限至'"
                prop="agentEndTime"
            >
              <date-picker
                  v-model:date="formData.agentEndTime"
                  :disabled-date="disabledDate"
                  placeholder="请选择期限"
                  @change="dateChange"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item
                v-if="formData.agentAttribute == 1"
                label="最低销量"
                prop="minSale"
            >

              <el-input
                  v-model.number="formData.minSale"
                  placeholder="请输入最低销量"
              >
                <template #append>
                  <span
                      v-if="formData.sellUnit"
                      style="margin-right: 10px"
                  >{{ getLabel('sell_unit', formData.sellUnit) }}/</span>
                  <el-select
                      v-model="formData.minSaleUnit"
                      placeholder=""
                      style="width: 100px"
                  >
                    <el-option
                        v-for="item in unitOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    />
                  </el-select>
                </template>
              </el-input>

            </el-form-item>
            <el-form-item
                v-else
                label="最低销量"
            >

              <el-input
                  v-model.number="formData.minSale"
                  placeholder="请输入最低销量"
              >
                <template #append>
                  <span
                      v-if="formData.sellUnit"
                      style="margin-right: 10px"
                  >{{ getLabel('sell_unit', formData.sellUnit) }}/</span>
                  <el-select
                      v-model="formData.minSaleUnit"
                      placeholder=""
                      style="width: 80px"
                  >
                    <el-option
                        v-for="item in unitOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    />
                  </el-select>
                </template>
              </el-input>

            </el-form-item>

          </el-col>

          <el-col :span="12">
            <el-form-item
                v-if="formData.agentAttribute == 1"
                label="销量保证金"
                prop="minSalePromise"
            >

              <!--                            <price-input v-model:data="formData.minSalePromise" placeholder="请输入销量保证金" is-unit unitStr="元"></price-input>-->

              <el-input
                  v-model.number="formData.minSalePromise"
                  placeholder="请输入销量保证金"
              />

            </el-form-item>
            <el-form-item
                v-else
                label="销量保证金"
            >

              <!--                            <price-input v-model:data="formData.minSalePromise" placeholder="请输入销量保证金" is-unit unitStr="元"></price-input>-->

              <el-input
                  v-model.number="formData.minSalePromise"
                  clearable
                  placeholder="请输入销量保证金"
              />

            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item
                label="负责营销职员"
                prop="headId"
            >
              <el-select
                  v-model="formData.headId"
                  placeholder="请选择营销职员"
                  @change="headChange"
              >
                <el-option
                    v-for="item in headOptions"
                    :key="item.id"
                    :label="item.realName"
                    :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item :label="type == 'agent'?'关联代理合同':'关联兼职合同'">
              <el-select
                  v-model="formData.contractId"
                  clearable=""
                  placeholder="请选择合同"
                  @change="contractChange"
              >
                <el-option
                    v-for="item in contractOptions"
                    :key="item.id"
                    :label="item.contractName"
                    :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item
                label="代理服务摘要名称"
                prop="abstract"
            >
              <el-input
                  v-model="formData.abstract"
                  clearable=""
                  placeholder="请输入代理服务摘要名称"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item
                label="其他约定"
                prop="remark"
            >
              <el-input
                  v-model="formData.remark"
                  clearable
                  placeholder="请输入其他约定"
              />
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button
              :disabled="disabled"
              type="primary"
              @click="dialogConfirm"
          >提交审核
          </el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script>
import {useRoute} from 'vue-router'
import {crmStore} from '@CRM/store'
import {defineComponent, getCurrentInstance, inject, onBeforeMount, reactive, ref, toRefs,} from 'vue'

export default defineComponent({
  name: 'AddProductDialog',
  props: {
    title: {
      type: String,
      default: '新增代理产品与价格',
    },
    type: {
      type: String,
      default: 'agent',
    },
    agentId: {
      type: Number,
      default: 0,
    },
  },
  setup(props, {emit}) {
    const route = useRoute()
    const currentInstance = getCurrentInstance()
    const api = inject('api')
    // const citys = area
    const citys = ref([])
    const props1 = reactive({
      multiple: true,
      expandTrigger: 'hover',
      label: 'regionName',
      value: 'regionCode',
    })
    const headOptions = ref([])
    const contractOptions = ref([])
    const rules = ref({
      productPopularName: [
        {
          required: true,
          message: '请选择产品',
          trigger: 'blur',
        },
      ],
      agentEndTime: [
        {
          type: 'date',
          required: true,
          message:
              props.type == 'agent' ? '请选择代理期限至' : '请选择兼职期限至',
          trigger: 'change',
        },
      ],
      agentAttribute: [
        {
          required: true,
          message: props.type == 'agent' ? '请选择代理属性' : '请选择兼职属性',
          trigger: 'change',
        },
      ],
      areas: [
        {
          required: true,
          message: '请选择代理地区',
          trigger: 'change',
        },
      ],
      tradePrice: [
        {
          required: true,
          message: '请输入交易价',
          trigger: 'blur',
        },
      ],
      minSale: [
        {
          required: true,
          message: '请输入最低销量',
          trigger: 'blur',
        },
      ],
      minSalePromise: [
        {
          required: true,
          message: '请输入销量保证金',
          trigger: 'blur',
        },
      ],
      headId: [
        {
          required: true,
          message: '请选择营销职员',
          trigger: 'change',
        },
      ],
      terminalType: [
        {
          required: true,
          message: '请选择可营销终端',
          trigger: 'change',
        },
      ],
    })

    var ruleForm = ref(null)
    var cascader = ref(null)
    var dialogVisible = ref(false)
    const unitOptions =
        crmStore.getters['dictionary/getDictionary']['sell_num_unit']
    const appOptions = crmStore.getters['dictionary/getDictionary']['app_mode']
    const attributeOptions =
        crmStore.getters['dictionary/getDictionary']['agent']
    const personOptions =
        crmStore.getters['dictionary/getDictionary']['agent_person']

    var data = reactive({
      formData: {
        productId: 0,
        productPopularName: '',
        approvalNumber: '',
        packSpecs: '',
        sellUnit: '',
        terminalType: '', // 终端客户类型
        agentAttribute: '', // 代理属
        areas: [],
        region: [],
        tradePrice: '', // 交易价
        agentEndTime: '', // 代理结束时间
        minSale: '', // 最低销量
        minSaleUnit: '1', // 最低销量单位
        minSalePromise: '', // 销量保证金
        headName: '',
        headId: '',
        remark: '', // 其他约定
        agentId: 0, // 代理商id
        contractId: '', // 合同id
        contractName: '', // 合同id
        abstract: '',
      },
      disabled: false,
    })

    const disabledDate = (time) => {
      return !(time.getTime() > Date.now())
    }

    const dialogConfirm = () => {
      ruleForm.value.validate((val) => {
        if (val) {
          data.disabled = true
          data.formData.agentId = props.agentId
              ? props.agentId
              : Number(route.query.id)
          data.formData.minSale = Number(data.formData.minSale)
          data.formData.tradePrice = Number(data.formData.tradePrice)
          data.formData.minSalePromise = Number(data.formData.minSalePromise)
          data.formData.contractId = Number(data.formData.contractId)
          if (data.formData.id) {
            api.signedAgent
                .AGENT_PRODUCT_EDIT(data.formData)
                .then((res) => {
                  if (!res.code) {
                    currentInstance.proxy.customMessage({
                      type: 'success',
                      message: '编辑成功',
                    })
                    emit('success')

                    handleClose()
                  } else {
                    currentInstance.proxy.customMessage({
                      type: 'error',
                      message: res.msg,
                    })
                    data.disabled = false
                  }
                })
                .catch((err) => {
                  data.disabled = false
                })
          } else {
            api.signedAgent
                .AGENT_PRODUCT_CREATE(data.formData)
                .then((res) => {
                  if (!res.code) {
                    currentInstance.proxy.customMessage({
                      type: 'success',
                      message: '添加成功',
                    })
                    emit('success')

                    handleClose()
                  } else {
                    currentInstance.proxy.customMessage({
                      type: 'error',
                      message: res.msg,
                    })
                    data.disabled = false
                  }
                })
                .catch((err) => {
                  data.disabled = false
                })
          }
        }
      })
    }

    const handleClose = () => {
      data.formData.approvalNumber = ''
      data.formData.packSpecs = ''
      data.formData.contractId = ''
      data.formData.abstract = ''
      data.formData.minSale = ''
      data.formData.minSalePromise = ''
      data.formData.areas = []
      data.formData.terminalType = ''
      data.disabled = false
      ruleForm.value.resetFields()
      dialogVisible.value = false
      setTimeout(() => {
        ruleForm.value.clearValidate()
      }, 100)
    }

    const openDialog = (a) => {
      if (a) {
        data.formData = JSON.parse(JSON.stringify(a))
        data.formData.areas = currentInstance.proxy.getCascaderAreaData(
            data.formData.region
        )
        getArea()
      }
      dialogVisible.value = true
    }

    const getArea = () => {
      if (data.formData.productId && data.formData.agentAttribute) {
        const pam = {
          productId: data.formData.productId,
          agentAttribute: data.formData.agentAttribute,
        }
        api.signedAgent
            .AGENT_PRODUCT_REGION(pam)
            .then((res) => {
              if (!res.code && res.data) {
                citys.value = res.data.region
              }
            })
            .catch()
      }
    }

    const attributeChange = () => {
      getArea()

      data.formData.areas = []
      data.formData.region = []
    }

    const productConfirm = (val) => {
      console.log(val)
      data.formData.productId = val.id
      data.formData.productPopularName = val.productPopularName
      data.formData.approvalNumber = val.approvalNumber
      data.formData.packSpecs = val.packSpecs
      data.formData.sellUnit = val.sellUnit

      getArea()
      data.formData.areas = []
      data.formData.region = []
    }

    const productClear = () => {
      data.formData.productId = 0
      data.formData.productPopularName = ''
      data.formData.approvalNumber = ''
      data.formData.packSpecs = ''
      data.formData.sellUnit = ''

      data.formData.areas = []
      data.formData.region = []
    }

    const areaChange = (val) => {
      const serve = currentInstance.proxy.getServeAreaData(
          val,
          cascader.value.getCheckedNodes()
      )
      data.formData.region = serve
    }

    const dateChange = (val) => {
      if (data.formData.date) {
        // formData.agentEndTime = currentInstance.proxy.dateFormat('yyyy-mm-dd',formData.date) + " 23:59:59"
        data.formData.agentEndTime = data.formData.date
      }
    }

    const headChange = (val) => {
      if (val) {
        const index = headOptions.value.findIndex((a) => a.id === val)
        if (index !== -1) {
          data.formData.headName = headOptions.value[index].realName
        }
      }
    }

    const contractChange = (val) => {
      if (val) {
        const index = contractOptions.value.findIndex((a) => a.id === val)
        if (index !== -1) {
          data.formData.contractName = contractOptions.value[index].contractName
        }
      } else {
        data.formData.contractName = ''
      }
    }

    const getContract = () => {
      const a = {
        objectId: props.agentId ? props.agentId : Number(route.query.id),
        contractObjectType: props.type,
      }
      api.common.VALID_CONTRACT_LIST(a).then((res) => {
        if (!res.code && res.data) {
          contractOptions.value = res.data.list
          console.log(contractOptions.value)
        }
      })
    }

    // 获取负责人
    const handlHead = () => {
      api.terminal.HEAD_PEOPLE(1).then((res) => {
        if (res.code === 0) {
          headOptions.value = res.data
        }
      })
    }

    onBeforeMount(() => {
      handlHead()
      getContract()
    })

    return {
      citys,
      props1,
      cascader,
      ruleForm,
      dialogVisible,
      ...toRefs(data),
      unitOptions,
      appOptions,
      attributeOptions,
      personOptions,
      rules,
      headOptions,
      contractOptions,

      dialogConfirm,
      handleClose,
      openDialog,
      productClear,
      areaChange,
      dateChange,
      productConfirm,
      headChange,
      contractChange,
      disabledDate,
      attributeChange,
    }
  },
})
</script>

<style lang="scss">
.add-product-dialog {
  .demo-ruleForm {
    .el-form-item {
      width: 100%;

      .el-cascader {
        width: 100%;
      }

      .el-input {
        width: 100%;
      }

      .el-select {
        width: 100%;
      }
    }
  }

  .special-input {
    display: flex;
    justify-content: space-between;

    .input-content {
      display: flex;
      width: 100%;

      .unit-view {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 80px;
        height: 40px;
        border: var(--el-input-border, var(--el-border-base));
        border-left: 0;
        box-sizing: border-box;
        border-radius: 0 5px 5px 0;
        background-color: #f5f5f5;
      }
    }

    .el-input {
      .el-input__inner {
        border-radius: 5px 0 0 5px;
      }
    }

    a {
      width: 120px;
      display: flex;
      justify-content: flex-end;
    }
  }

  .sale-view {
    display: flex;

    .el-input {
      .el-input__inner {
        border-radius: 5px 0 0 5px;
      }
    }

    .el-select {
      width: 100px;
      min-width: 100px;

      .el-input__inner {
        border-radius: 0 5px 5px 0;
      }
    }
  }
}
</style>
